const app = getApp();
var util = require('../../utils/util.js');
var picRoot = app.data.picRoot;
var url = app.data.url;
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    envPic: [
      'http://www.runoob.com/try/demo_source/paris.jpg', 'http://www.runoob.com/try/demo_source/paris.jpg'
    ],
    beginDayStyle: [{
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#AAD4F5'
      },
      {
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#AAD4F5'
      }
    ],
    outDayStyle: [{
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#84e7d0'
      },
      {
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#84e7d0'
      }
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    activeNames: ['1'],
    addr: '广东省云浮市新兴县祥顺大酒店',
    businessTime: '营业时间:每天8点 ~ 每天17点',
    serviceContent: 'aaasssss',
    lat: '',
    lot: '',
    merchantId: '',
    phone: '0766-2899668',
    arr: [],
    name: '',
    detailShow: false,
    roomDetailShow: false,
    inRoomDateShow: false,
    outRoomDateShow: false,
    beginDateStr: '',
    endDateStr: '',
    mainFileList: [],
    mainImg: false,
    overLayShow: false,
    show: false,
    roomFileList: [],
    radio: '0',
    roomName: '',
    roomDesc: '',
    roomNum: '',
    itemDiscountPrice: 0,
    itemPrice: 0,
    roomBtn: 0,
    unitList: [],
    saveRoomImgPath: [],
    id: '',
    putAwayStatus: true
    
  },
  toPrcie: function(option){
    console.log(option);
    let _that = this;
    let item = option.currentTarget.dataset.item;
    let title = item.roomName;
    let merchantId = _that.data.merchantId;
    let roomId = item.id;
    wx.navigateTo({
      url: '../../pages/room-price/index?merchantId=' + merchantId + "&roomId=" + roomId + "&title=" + title,
    })
  },
  /**
   * 删除
   */
  deleteUnit: function(option) {
    let _that = this;
    let id = _that.data.id;
    let uuid = _that.data.uuid;
    let merchantId = _that.data.merchantId;
    let roomName = _that.data.roomName;
    Dialog.confirm({
      title: '提醒',
      message: '是否确定删除【' + roomName + "】"
    }).then(() => {
      wx.request({
        url: url + '/HotelSystemApi/deleteRoom',
        data: {
          id: id,
          uuid: uuid
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            _that.setData({
              show: false
            })
            _that.queryData(uuid, merchantId);
            wx.showToast({
              title: "删除成功!",
              icon: "success",
              duration: 2000
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        }
      })
    }).catch(() => {
      // on cancel
    });



  },
  insertOrUpdate: function(option) {
    let _that = this;
    let roomName = _that.data.roomName;
    let roomDesc = _that.data.roomDesc;
    let merchantId = _that.data.merchantId;
    let roomNum = _that.data.roomNum;
    let itemDiscountPrice = _that.data.itemDiscountPrice;
    let itemPrice = _that.data.itemPrice;
    let radio = _that.data.radio;
    let putAwayStatus = _that.data.putAwayStatus;

    // 处理图片
    let saveRoomImgPath = _that.data.saveRoomImgPath;
    console.log(saveRoomImgPath);
    let imgPath = '';
    for (var i = 0; i < saveRoomImgPath.length; i++) {
      imgPath += saveRoomImgPath[i];
      if (i != saveRoomImgPath - 1) {
        imgPath += ",";
      }
    }
    console.log(imgPath);
    let payType;
    if (radio == '0') {
      payType = 0
    } else {
      payType = 1
    }
    let uuid = _that.data.uuid;

    let method = option.currentTarget.dataset.method;
    let tempUrl;
    let tempData;
    if (method == 0) {
      tempUrl = url + '/HotelSystemApi/insertRoom';
      tempData = {
        roomName: roomName,
        roomDesc: roomDesc,
        merchantId: merchantId,
        originalPrice: itemPrice,
        discountPrice: itemDiscountPrice,
        payType: payType,
        createUserName: uuid,
        updateUserName: uuid,
        img: imgPath,
        putAwayStatus: putAwayStatus == true ? 0 : 1
      }
    } else {
      tempUrl = url + '/HotelSystemApi/editRoom';
      let id = _that.data.id;
      tempData = {
        id: id,
        roomName: roomName,
        roomDesc: roomDesc,
        merchantId: merchantId,
        originalPrice: itemPrice,
        discountPrice: itemDiscountPrice,
        payType: payType,
        createUserName: uuid,
        updateUserName: uuid,
        img: imgPath,
        putAwayStatus: putAwayStatus == true ? 0 : 1
      }
    }
    wx.request({
      url: tempUrl,
      data: tempData,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          _that.setData({
            show: false
          })
          _that.queryData(uuid, merchantId);
          wx.showToast({
            title: '操作成功!',
            icon: "success",
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })

  },

  /***
   * 表单start
   */
  /**上下架状态 */
  onPutAwayStatusChange: function(event) {
    let _that = this;
    _that.setData({
      putAwayStatus: event.detail
    });
  },
  /**
 * 结算类型
 */
  onRadioChange: function (event) {
    let _that = this;
    _that.setData({
      radio: event.detail
    });
  },
  /**
   * 折扣价
   */
  onDiscountPriceChange: function (event) {
    let _that = this;
    _that.setData({
      itemDiscountPrice: event.detail
    });
  },

  /**
   * 原价
   */
  onPriceChange: function (event) {
    let _that = this;
    _that.setData({
      itemPrice: event.detail
    });
  },
  /**
   * 房间名称
   */
  onRoomNameChange: function(event) {
    let _that = this;
    _that.setData({
      roomName: event.detail
    });
  },
  /**
   * 简介
   */
  onRoomDescChange: function(event) {
    let _that = this;
    _that.setData({
      roomDesc: event.detail
    });
  },
  /**
   * 房间数量
   */

  onRoomNumChange: function(event) {
    let _that = this;
    _that.setData({
      roomNum: event.detail
    });
  },


  /**
   * 表单end
   */

  /**
   * 删除图片
   */
  deleteImg: function(option) {
    let _that = this;
    Dialog.confirm({
      title: '是否删除',
      message: '删除后请点击按钮保存!'
    }).then(() => {
      // on confirm
      let saveRoomImgPath = _that.data.saveRoomImgPath[option.detail.index];
      wx.request({
        url: url + '/ItemSystemApi/insertDeleteImg',
        data: {
          img: saveRoomImgPath
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            // 重新加载
            let {
              roomFileList = []
            } = _that.data;
            let saveRoomImgPath = _that.data.saveRoomImgPath;
            roomFileList.splice(option.detail.index, 1);
            saveRoomImgPath.splice(option.detail.index, 1);
            _that.setData({
              roomFileList: roomFileList,
              saveRoomImgPath: saveRoomImgPath
            });
            // _that.queryData(merchantId);
            wx.showToast({
              title: "删除成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function(res) {
          console.info('submit fail');
        },
        complete: function(res) {
          console.info('submit complete');
        }
      })

    })
  },
  /**
   * 打开弹框
   */
  showPopup(option) {
    console.log(option);
    let _that = this;
    let roomBtn = option.currentTarget.dataset.roombtn;
    let roomFileList = _that.data.roomFileList;
    roomFileList = [];
    let saveRoomImgPath = _that.data.saveRoomImgPath;
    saveRoomImgPath = [];
    if (roomBtn == 1) {
      let radio = option.currentTarget.dataset.radio + "";
      let roomName = option.currentTarget.dataset.name;
      let roomDesc = option.currentTarget.dataset.desc;
      let roomNum = option.currentTarget.dataset.num;
      let itemDiscountPrice = option.currentTarget.dataset.itemdiscountprice;
      let itemPrice = option.currentTarget.dataset.itemprice;
      let img = option.currentTarget.dataset.img;
      let id = option.currentTarget.dataset.id;
      let putAwayStatus = option.currentTarget.dataset.putawaystatus;
      let imgArr = img.split(",");
      for (var i = 0; i < imgArr.length; i++) {
        if (imgArr[i] != '') {
          roomFileList.push({
            url: picRoot + imgArr[i]
          });
          saveRoomImgPath.push(imgArr[i]);
        }
      }
      _that.setData({
        id: id,
        radio: radio,
        roomName: roomName,
        roomDesc: roomDesc,
        roomNum: roomNum,
        itemDiscountPrice: itemDiscountPrice,
        itemPrice: itemPrice,
        roomFileList: roomFileList,
        saveRoomImgPath: saveRoomImgPath,
        putAwayStatus: putAwayStatus == 0 ? true : false
      })
    } else {
      console.log("333");
      _that.setData({
        id: '',
        radio: '0',
        roomName: '',
        roomDesc: '',
        roomNum: '',
        itemDiscountPrice: '',
        itemPrice: '',
        roomFileList: [],
        saveRoomImgPath: [],
        putAwayStatus: true
      })
    }
    _that.setData({
      roomBtn: roomBtn,
      show: true
    })
  },
  onRoomClose() {
    this.setData({
      show: false
    });
  },
  toShowHotel: function(option) {
    let _that = this;
    let merchantId = _that.data.merchantId;
    wx.navigateTo({
      url: '/pages/show-hotel/index?merchantId=' + merchantId
    })
  },
  /**弹框 */
  onOverLayShow() {
    this.setData({
      overLayShow: true
    });
  },
  onOverLayHide() {
    this.setData({
      overLayShow: false
    });
  },
  toMainImg: function() {
    let _that = this;
    _that.setData({
      mainImg: true
    })
  },
  onMainImgClose: function() {
    let _that = this;
    _that.setData({
      mainImg: false
    })
  },
  roomAfterRead: function(event) {
    const {
      file
    } = event.detail;
    console.log(file);
    let _that = this;
    let saveRoomImgPath = _that.data.saveRoomImgPath;
    console.log("=====:" + saveRoomImgPath);
    _that.onOverLayShow();
    for (var i = 0; i < file.length; i++) {
      wx.uploadFile({
        url: url + '/HotelSystemApi/uploadPic',
        filePath: file[i].path,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'file',
        success(res) {
          // 上传完成需要更新 fileList
          const {
            roomFileList = []
          } = _that.data;
          console.log(roomFileList);
          roomFileList.push({ ...file,
            url: picRoot + res.data
          });
          console.log(roomFileList);
          _that.setData({
            roomFileList
          });
          saveRoomImgPath.push(res.data);
          _that.setData({
            saveRoomImgPath: saveRoomImgPath
          });
          if (i == (file.length)) {
            _that.onOverLayHide();
          }
        }
      });
    }
  },
  onRadioChange: function(event) {
    let _that = this;
    _that.setData({
      radio: event.detail
    });
  },
  afterRead: function(event) {
    const {
      file
    } = event.detail;
    console.log(file);
    let _that = this;
    _that.onOverLayShow();
    for (var i = 0; i < file.length; i++) {
      wx.uploadFile({
        url: url + '/HotelSystemApi/uploadPic',
        filePath: file[i].path,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'file',
        success(res) {
          // 上传完成需要更新 fileList
          const {
            mainFileList = []
          } = _that.data;
          mainFileList.push({ ...file,
            url: picRoot + res.data
          });
          _that.setData({
            mainFileList
          });
          if (i == file.length) {
            _that.onOverLayHide();
          }
        }
      });
    }
  },
  emptyBeginTime: function(options) {
    let _that = this;
    _that.setData({
      beginDateStr: ''
    })
  },
  emptyEndTime: function(options) {
    let _that = this;
    _that.setData({
      endDateStr: ''
    })
  },
  confirmBeginDate: function() {
    let _that = this;
    let str = _that.data.beginDateStr;
    if (!str) {
      wx.showToast({
        title: "请选择入住时间",
        icon: "none",
        duration: 2000
      })
      return;
    }
    _that.setData({
      inRoomDateShow: false
    });
  },
  confirmEndDate: function() {
    let _that = this;
    let str = _that.data.endDateStr;
    if (!str) {
      wx.showToast({
        title: "请选择离开时间",
        icon: "none",
        duration: 2000
      })
      return;
    }
    _that.setData({
      outRoomDateShow: false
    });
  },
  inDayClick: function(event) {
    let clickDay = event.detail.day;
    let changeDay = `beginDayStyle[1].day`;
    let changeBg = `beginDayStyle[1].background`;
    let year = event.detail.year;
    let month = event.detail.month;
    month = month < 10 ? ('0' + month) : month;
    let day = event.detail.day;
    day = day < 10 ? ('0' + day) : day;
    let str = year + "-" + month + "-" + day;
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#FFdd55",
      beginDateStr: str
    })
  },
  outDayClick: function(event) {
    let clickDay = event.detail.day;
    let changeDay = `outDayStyle[1].day`;
    let changeBg = `outDayStyle[1].background`;
    let year = event.detail.year;
    let month = event.detail.month;
    month = month < 10 ? ('0' + month) : month;
    let day = event.detail.day;
    day = day < 10 ? ('0' + day) : day;
    let str = year + "-" + month + "-" + day;
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#FFdd55",
      endDateStr: str
    })
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let merchantId = options.merchantId;
    console.log(options);
    let _that = this;
    _that.setData({
      merchantId: merchantId
    })
    wx.setNavigationBarTitle({
      title: "酒店管理"
    })
    wx.getStorage({
      key: "uuid",
      success(res) {
        _that.setData({
          uuid: res.data
          // merchantId = 40;
        })
        // 加载房间
        _that.queryData(res.data, merchantId);
      }
    })


  },
  /**
   * 加载房间
   */
  queryData: function(uuid, merchantId) {
    let _that = this;
    console.log(uuid);
    console.log(merchantId);
    wx.request({
      url: url + '/HotelSystemApi/listPageRoom',
      data: {
        uuid: uuid,
        merchantId: merchantId,
        invoking: 1
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          console.log(res.data.data);

          _that.setData({
            unitList: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
  },

  /**
   * 打开入住时间日历
   */
  openBeginDate: function(options) {
    let _that = this;
    _that.setData({
      inRoomDateShow: true
    });
  },
  closeBeginDate: function() {
    let _that = this;
    _that.setData({
      inRoomDateShow: false
    });
  },

  /**
   * 打开离开时间日历
   */
  openOutDate: function(options) {
    let _that = this;
    _that.setData({
      outRoomDateShow: true
    });
  },
  closeOutDate: function() {
    let _that = this;
    _that.setData({
      outRoomDateShow: false
    });
  },

  /**
   * 打开房间详情
   */
  openRoomDetail: function(options) {
    let _that = this;
    _that.setData({
      roomDetailShow: true
    });
  },
  closeRoomDetail: function() {
    let _that = this;
    _that.setData({
      roomDetailShow: false
    });
  },
  /***
   * 打开酒店详情
   */
  toHotelDetail: function(oiptions) {
    let _that = this;
    _that.setData({
      detailShow: true
    });
  },
  onClose() {
    let _that = this;
    _that.setData({
      detailShow: false
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})